﻿#include"seqlist.h"

//扩容
void Dilatation(SeqList* ps)
{
	assert(ps != NULL);
	SLDateType* temp = NULL;
	temp = realloc(ps->a, 2 * (ps->capacity) * sizeof(SLDateType));
	if (temp == NULL)
	{
		printf("realloc fail!\n");
		exit(-1);
	}
	ps->a = temp;
	ps->capacity = ps->capacity * 2;
}

void SeqListInit(SeqList* ps)
{
	assert(ps != NULL);
	ps->a = (SLDateType*)malloc(sizeof(SLDateType) * 3);
	if (*ps->a == NULL)
	{
		printf("malloc fail!\n");
		exit(-1);
	}
	ps->capacity = 3;
	ps->size = 0;
}

void SeqListDestroy(SeqList* ps)
{
	assert(ps != NULL);
	free(ps->a);
	ps->a = NULL;
}

void SeqListPrint(SeqList* ps)
{
	assert(ps != NULL);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

void SeqListPushBack(SeqList* ps, SLDateType x)
{
	assert(ps != NULL);
	if (ps->size == ps->capacity)
	{
		Dilatation(ps);
	}

	ps->a[ps->size] = x;
	ps->size++;
}

void SeqListPushFront(SeqList* ps, SLDateType x)
{
	assert(ps != NULL);
	if (ps->size == ps->capacity)
	{
		Dilatation(ps);
	}

	for (int i = ps->size - 1; i >= 0; i--)
	{
		ps->a[i + 1] = ps->a[i];
	}
	ps->a[0] = x;
	ps->size++;
}

void SeqListPopFront(SeqList* ps)
{
	assert(ps != NULL);
	assert(ps->size > 0);
	for (int i = 1; i < ps->size; i++)
	{
		ps->a[i - 1] = ps->a[i];
	}
	ps->size--;
}

void SeqListPopBack(SeqList* ps)
{
	assert(ps != NULL);
	assert(ps->size > 0);
	ps->size--;
}
int SeqListFind(SeqList* ps, SLDateType x)
{
	assert(ps!=NULL);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SeqListInsert(SeqList* ps, int pos, SLDateType x)
{
	assert(ps != NULL);
	assert(pos >= 0 && pos < ps->size);
	if (ps->size == ps->capacity)
	{
		Dilatation(ps);
	}
	for (int i = ps->size - 1; i >= pos; i--)
	{
		ps->a[i + 1] = ps->a[i];
	}
	ps->a[pos] = x;
	ps->size++;
}

void SeqListErase(SeqList* ps, int pos)
{
	assert(ps != NULL);
	assert(pos >= 0 && pos < ps->size);
	assert(ps->size > 0);
	for (int i = pos + 1; i < ps->size; i++)
	{
		ps->a[i - 1] = ps->a[i];
	}
	ps->size--;
}